package com.dj.common.web.service.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;

import com.alibaba.fastjson.JSONObject;
import com.dj.common.web.service.ValueObject;
import com.dj.common.web.vo.PageAndSortVo;
import com.dj.common.web.vo.PageData;

public class BaseWebServiceImpl<VO extends ValueObject> {

	public PageAndSortVo<PageData> convertToPageAndSortVo(Pageable pageRequest,
			PageData vo, boolean... isCount) {
		PageAndSortVo<PageData> pageVo = new PageAndSortVo<>();
		if (null != pageRequest) {
			pageVo.setOffset(pageRequest.getOffset());
			pageVo.setLimit(pageRequest.getPageSize());
			pageVo.setSort(getSort(pageRequest.getSort()));
			if (null != isCount && isCount.length > 0) {
				pageVo.setCount(isCount[0]);
			}
		} else {
			pageVo.setOffset(0);
			pageVo.setLimit(0);
		}
		pageVo.setVo(vo);
		return pageVo;

	}

	/**
	 * 组装排序的字段
	 * 
	 * @param sort
	 * @return
	 */
	protected String getSort(Sort sort) {
		if (sort == null)
			return null;

		Iterator<Order> iterator = sort.iterator();
		String orderBySql = "";
		while (iterator.hasNext()) {
			Order order = iterator.next();
			String fieldName = order.getProperty();
			String sortDirection = order.getDirection().name();
			orderBySql += fieldName + ":" + sortDirection + ",";
		}
		return orderBySql.substring(0, orderBySql.length() - 1);
	}

	public Map<String, String> pagePutMap(Map<String, String> map, Pageable pageRequest) throws Exception {
		if(null==map){
			map = new HashMap<String, String>();
		}
		map.put("offset",pageRequest.getOffset()+"");
		map.put("pageSize",pageRequest.getPageSize()+"");
		map.put("page",(pageRequest.getPageNumber()-1)+"");
		Iterator<Order> iterator = pageRequest.getSort().iterator();
		while (iterator.hasNext()) {
			Order order = iterator.next();
			String fieldName = order.getProperty();
			String sortDirection = order.getDirection().name();
			map.put("sort",fieldName);
			map.put("desc",sortDirection);
		}
		return map;
	}
	@SuppressWarnings("unchecked")
	public Map<String, String> beanPutMap(Map<String, String> map, Object obj) throws Exception {
		if(null==map){
			map = new HashMap<String, String>();
		}
		Map<String,Object> map2 = (Map<String,Object>)JSONObject.toJSON(obj);
		if(null!=map2){
			for (Map.Entry<String,Object> entry : map2.entrySet()) {
				Object v = entry.getValue();
				if(null!=v){
					map.put(entry.getKey(), v.toString());
				}
			}
		}
		return map;
	}
}
